//
//  YWQicheController.m
//  YueshengToutiao
//
//  Created by jun peng on 2022/5/22.
//  Copyright © 2022 YW. All rights reserved.
//

#import "YWQicheController.h"
#import "YWHomeRecommendVedioCell.h"
#import "YWGetNewsListParam.h"
#import "YWGetNewsListStatus.h"
#import "YWGetNewsResultStatus.h"
#import "YWGetNewsDataStatus.h"
#import "YWGetNewsTool3.h"
#import "YWListCellDelegate.h"
#import "YWNoContentView2.h"

#import "YWVideoView2.h"
#import "YWHengAnimationVedioView.h"

#import "YWHengVideoDetailController.h"

#import "AppDelegate.h"

//#define headerViewVedioViewHeight 210


@interface YWQicheController ()<UITableViewDataSource, UITableViewDelegate,YWListCellDelegate,YWNoContentView2Delegate,YWVideoView2Delegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *statusArray;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic, strong) UIView * vedioBgView; // 播放器BgView
@property (nonatomic, strong) YWVideoView2 * vedioView; // 播放器

@property (weak, nonatomic) IBOutlet UIView *bgView;


@property(nonatomic,strong)UIView *hengBgWhiteView;
@property(nonatomic,strong)YWHengAnimationVedioView *hengAnimationVedioView;

@property(nonatomic,assign)BOOL isGoToHengVideoDetailVCToDisAppearView;


@end

@implementation YWQicheController

-(UIView *)hengBgWhiteView{
    if (_hengBgWhiteView == nil) {
        
        _hengBgWhiteView = [[UIView alloc] init];
        _hengBgWhiteView.frame = CGRectMake(0, 0, Wi, He);
        
        _hengBgWhiteView.backgroundColor = [UIColor whiteColor];
        _hengBgWhiteView.alpha = 0;
    }
    return _hengBgWhiteView;
}

-(YWHengAnimationVedioView *)hengAnimationVedioView{
    if (_hengAnimationVedioView == nil) {
        _hengAnimationVedioView = [YWHengAnimationVedioView videoView];
        
        _hengAnimationVedioView.backgroundColor = [UIColor blackColor];
    }
    return _hengAnimationVedioView;
}



-(NSMutableArray *)statusArray{
    if (_statusArray == nil) {
        _statusArray = [NSMutableArray array];
    }
    return _statusArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.title = @"汽车之家";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    MJWeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [weakSelf loadNewsData];

    }];
    
    [self.tableView.mj_header beginRefreshing];
    
    // 创建播放器
    self.vedioView = [YWVideoView2 videoView];
    self.vedioView.delegate = self;
    self.vedioBgView = [UIView new];
    [self.tableView addSubview:self.vedioBgView];
    self.vedioBgView.backgroundColor = [UIColor blackColor];
    self.vedioView.backgroundColor = [UIColor blackColor];
    self.vedioBgView.hidden = YES;
    [self.vedioBgView addSubview:self.vedioView];
    self.vedioView.frame = self.vedioBgView.bounds;
    
}


-(void)loadNewsData{
    
    self.page = 1;
    YWGetNewsListParam *param = [[YWGetNewsListParam alloc] init];
    param.pagesize = @"15";
    param.currentpage = [NSString stringWithFormat:@"%ld",(long)self.page];
    
    NSInteger remarks = 2;
    param.type = [NSString stringWithFormat:@"%ld",(long)remarks];
    
    NSString *userID = self.meStatus.userStatus.Id;
      if (userID != nil) {
           param.userid = userID;
       }
       else{
           
           param.userid = @"";
       }
    
    [YWGetNewsTool3 getNewsListStatusesWithParameters:param success:^(YWGetNewsListStatus * _Nonnull status) {
        
               [self.tableView.mj_header endRefreshing];
              [self.noContentView removeFromSuperview];
        
        //先停止播放
        [self.vedioView stopPlay];
        
               if (status.IsSuccess.integerValue == 1) {
                   
                   self.statusArray = [NSMutableArray arrayWithArray:status.ResultObj.PageInfo];
                   
                   [self.tableView reloadData];
                   
                   //预加载
                   NSMutableArray *urlArray = [NSMutableArray array];
                   for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
                       [urlArray addObject:dataStatus.FileUrl];
                   }
                   YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
                   [playerManager preLoadUrlArray:urlArray];
                   
                   
                   //假如少于就不需要添加上拉控件了
                  if (status.ResultObj.PageInfo.count == param.pagesize.integerValue) {
                     MJWeakSelf
                      //添加上拉刷新控件
                     self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

                         [weakSelf loadMoreData];
                     }];
                      
                   }
                   
                   
                   //再寻找需不需要播放
                   [self scrollToStartPlay:self.tableView];
                   
               }
               else{
                   
                   self.statusArray = [NSMutableArray array];
                   
                   [self.tableView reloadData];
                   
                   [self.view addSubview:self.noContentView];
                   
                   self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
                   
                   self.noContentView.noContentType = YWNoContentView2Type_NoContent;
                   
                   
                   
               }
    } failure:^(NSError * _Nonnull error) {
        
        [self.view addSubview:self.noContentView];
        
        self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
        
        self.noContentView.noContentType = YWNoContentView2Type_Error404;
    }];
    
    
}

-(void)noContentView2DidClickRefreshBtn:(YWNoContentView2 *)noContentView2{
    
    [self loadNewsData];
   
    
}

//加载更多
-(void)loadMoreData{
    
    self.page ++;
    YWGetNewsListParam *param = [[YWGetNewsListParam alloc] init];
    param.pagesize = @"15";
    param.currentpage = [NSString stringWithFormat:@"%ld",(long)self.page];
    
    NSInteger remarks = 2;
    param.type = [NSString stringWithFormat:@"%ld",(long)remarks];
    
    NSString *userID = self.meStatus.userStatus.Id;
      if (userID != nil) {
           param.userid = userID;
       }
       else{
           
           param.userid = @"";
       }
    [YWGetNewsTool3 getNewsListStatusesWithParameters:param success:^(YWGetNewsListStatus * _Nonnull status) {
        
        //移除上拉
        [self.tableView.mj_footer endRefreshing];
        if (status.IsSuccess.integerValue == 1) {
            
            [self.statusArray addObjectsFromArray:status.ResultObj.PageInfo];
            
            [self.tableView reloadData];
            
            //预加载
            NSMutableArray *urlArray = [NSMutableArray array];
            for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
                [urlArray addObject:dataStatus.FileUrl];
            }
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            [playerManager preLoadUrlArray:urlArray];
            
        }
        else{
            
            //它做的接口没数据是走这里的、所以可以直接移除footer
            [self.tableView.mj_footer removeFromSuperview];
            [MBProgressHUD showError:status.Message];
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        
        //移除上拉
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"服务器繁忙，请稍后再试"];
    }];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.statusArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWGetNewsDataStatus *status = self.statusArray[indexPath.row];
    if (status.cellType == YWCellTypeVideo){
        
        YWHomeRecommendVedioCell *cell = [YWHomeRecommendVedioCell cellWithTableView:tableView];
        
        cell.status = status;
        cell.delegate = self;
        
         return cell;
        
    }
    else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    tableView.rowHeight = UITableViewAutomaticDimension;

    tableView.estimatedRowHeight = 416;

    return tableView.rowHeight;
    
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //跳去下一页
    
    YWGetNewsDataStatus *status = self.statusArray[indexPath.row];
    
    YWHomeRecommendVedioCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    self.vedioView.index = indexPath.row;
    
    //是不是因为去横视频详情VC而离开本界面
    self.isGoToHengVideoDetailVCToDisAppearView = YES;
    
//看URL是否一致、是的话就continue、不是的话就start
    //1、hengAnimationVedioView开始播放/继续播放
    if ([self.vedioView.urlString isEqualToString:status.FileUrl]) {
        
        [self.hengAnimationVedioView continuePlayWithAnthorViewWithUrl:status.FileUrl WithMute:NO];
    }
    else{
        [self.hengAnimationVedioView startPlayWithUrl:status.FileUrl withMute:NO];
    }
    
    //2、添加
    [[UIApplication sharedApplication].keyWindow addSubview:self.hengBgWhiteView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.hengAnimationVedioView];
    
//这里利用给你的cell来转换frame
    //3、初始化位置d
    CGRect startRect = [cell.contentView convertRect:cell.videoBgView.frame toView:[UIApplication sharedApplication].keyWindow];
    
    self.hengAnimationVedioView.frame = startRect;
    
    //4、动画
    [UIView animateWithDuration:0.3 animations:^{
        
        self.hengBgWhiteView.alpha = 1;
        self.hengAnimationVedioView.frame = CGRectMake(0, self.navBar.height, Wi, headerViewVedioViewHeight);
    }completion:^(BOOL finished) {
        
        //5、弹出新的VC
        YWHengVideoDetailController *vc = [[YWHengVideoDetailController alloc] initWithNibName:@"YWHengVideoDetailController" bundle:nil];
//        vc.delegate = self;
        vc.status = status;
        
        [self.navigationController pushViewController:vc animated:NO];
        
        //6、移除动画view
        self.hengBgWhiteView.alpha = 0;
        [self.hengAnimationVedioView removeFromSuperview];
        [self.hengBgWhiteView removeFromSuperview];
        
        
    }];
    
   
}

-(void)listCell:(id)listCell didClickContentWithDataStatus:(YWGetNewsDataStatus *)status{
    
    //跳去下一页
    YWHomeRecommendVedioCell *cell = (YWHomeRecommendVedioCell *)listCell;
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    self.vedioView.index = indexPath.row;
    
    //是不是因为去横视频详情VC而离开本界面
    self.isGoToHengVideoDetailVCToDisAppearView = YES;
    
//看URL是否一致、是的话就continue、不是的话就start
    //1、hengAnimationVedioView开始播放/继续播放
    if ([self.vedioView.urlString isEqualToString:status.FileUrl]) {
        
        [self.hengAnimationVedioView continuePlayWithAnthorViewWithUrl:status.FileUrl WithMute:NO];
    }
    else{
        [self.hengAnimationVedioView startPlayWithUrl:status.FileUrl withMute:NO];
    }
    
    //2、添加
    [[UIApplication sharedApplication].keyWindow addSubview:self.hengBgWhiteView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.hengAnimationVedioView];
    
//这里利用给你的cell来转换frame
    //3、初始化位置d
    CGRect startRect = [cell.contentView convertRect:cell.videoBgView.frame toView:[UIApplication sharedApplication].keyWindow];
    
    self.hengAnimationVedioView.frame = startRect;
    
    //4、动画
    [UIView animateWithDuration:0.3 animations:^{
        
        self.hengBgWhiteView.alpha = 1;
        self.hengAnimationVedioView.frame = CGRectMake(0, self.navBar.height, Wi, headerViewVedioViewHeight);
    }completion:^(BOOL finished) {
        
        //5、弹出新的VC
        YWHengVideoDetailController *vc = [[YWHengVideoDetailController alloc] initWithNibName:@"YWHengVideoDetailController" bundle:nil];
//        vc.delegate = self;
        vc.status = status;
        
        [self.navigationController pushViewController:vc animated:NO];
        
        //6、移除动画view
        self.hengBgWhiteView.alpha = 0;
        [self.hengAnimationVedioView removeFromSuperview];
        [self.hengBgWhiteView removeFromSuperview];
        
        
    }];
    
    

    
}


-(void)listCell:(id)listCell didClickPlayVideoWithDataStatus:(YWGetNewsDataStatus *)status{
    
    //这里是播放
    
    YWHomeRecommendVedioCell *cell = (YWHomeRecommendVedioCell *)listCell;
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    self.vedioView.index = indexPath.row;
    
    [self.vedioView startPlayWithUrl:status.FileUrl withMute:NO];
    
    //添加位置
    [self.tableView addSubview:self.vedioBgView];
    
    //cell转换位置
    CGRect rects = [cell.contentView convertRect:cell.videoBgView.frame toView:self.tableView];
    
    self.vedioBgView.frame = rects;
    
    self.vedioView.frame = self.vedioBgView.bounds;

    self.vedioBgView.layer.cornerRadius = cell.videoBgView.layer.cornerRadius;
    self.vedioBgView.clipsToBounds = YES;

    
    self.vedioBgView.hidden = NO;
    
    //点击做移动cell位置到中间
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

}



-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (decelerate == YES) {

//        [self scrollToStartPlay:scrollView]; //这个和下面的减速可能冲突会出现滚动播放卡顿所以这个不要
    }
    else{

        [self scrollToStartPlay:scrollView];
    }

    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self scrollToStartPlay:scrollView];
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.vedioView.isPlaying_containPause == YES) {

         //正在播放状态
        NSInteger index = self.vedioView.index;

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];

        id cell = [self.tableView cellForRowAtIndexPath:indexPath];

        YWLog(@"%@",[cell class]);


        //点击更多、是重新刷新的过程、由于有些文章太长、导致下面的本来正在播放视频cell已经超出了屏幕的可是范围，而根据indexPath拿回之前的视频cell是null的（reloadData之后cell还没有创建出来、要第一次见到cell、cell才会被创建），所以要写下面的两步、避免出现vedioView在长文章上面
        if ([cell isKindOfClass:[NSNull class]] || cell == nil) {

            [self.vedioView stopPlay];
            self.vedioBgView.hidden = YES;


            return;
        }

        if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
            YWHomeRecommendVedioCell *vedioCell = (YWHomeRecommendVedioCell *)cell;

//其实这里重新赋值rect可能不需要、因为本来就是add在了tableView上
            //转换父控件所在位置
            CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

            //不断改变vedioBgView位置
            self.vedioBgView.frame = rects;

            self.vedioView.frame = self.vedioBgView.bounds;

            YWLog(@"rects：%@",NSStringFromCGRect(rects));

        //    判断播放视频的cell是否离开了屏幕
            CGRect cellRect = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.bgView];

            //增加了一个条件不是横屏（因为有时切换为横屏时候cell离开了屏幕导致播放器被stop了）、、、但是假如是横屏切换到竖屏有时候也会走这里、因为tableView的高度由矮变高过程cell会可能离开屏幕，所以对于本VC使用该控件Pager暂时无法保证横屏切换到竖屏可以继续播放而不走这里、、、除非你又增加一些属性表明当前是横屏切换成竖屏状态而不走这里之类的、这里先暂时不理了
            if (((cellRect.origin.y < -cellRect.size.height) || (cellRect.origin.y > self.bgView.height)) && !isLanscape) {
                [self.vedioView stopPlay];
                self.vedioBgView.hidden = YES;
            }

            YWLog(@"%@",NSStringFromCGRect(cellRect));

        }
     

    }
    
}


-(void)scrollToStartPlay:(UIScrollView *)scrollView{
    
    //我这里用了isPlaying，没有用isPlaying_containPause
    if(self.vedioView.isPlaying == NO)  {
        
        NSArray *cellArray = [self.tableView visibleCells];
        
        YWLog(@"cellArray_count:%ld",cellArray.count);

          for (id cell in cellArray) {
              
            if ([cell isKindOfClass:[YWHomeRecommendVedioCell class]]) {
                 
                YWHomeRecommendVedioCell *vedioCell = (YWHomeRecommendVedioCell *)cell;
                
                  NSIndexPath *indexPath = [self.tableView indexPathForCell:vedioCell];


                  //播放器中心距离bgView中心在一定距离才能播放
                  CGRect cellRect = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.bgView];
                  
                CGFloat videoCenterY = cellRect.origin.y + cellRect.size.height/2;
                CGFloat bgViewCenterY = self.bgView.height/2;
                
                CGFloat absY = fabs(videoCenterY - bgViewCenterY);
                
                //absY > fabs(bgViewCenterY - cellRect.size.height/2这个意思是整个videoView都要露出来才播放
                if (absY > fabs(bgViewCenterY - cellRect.size.height/2)) { //假如距离太远就寻找下一个播放器
                    continue;
                }
                  
                  
                  //转换父控件所在位置
                  CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

                  self.vedioBgView.frame = rects;

                  self.vedioView.frame = self.vedioBgView.bounds;

                  self.vedioView.index = indexPath.row;

                  YWGetNewsDataStatus *vedioStatus = self.statusArray[indexPath.row];
                
                
                  [self.vedioView startPlayWithUrl:vedioStatus.FileUrl withMute:NO];
                
                //添加位置
                [self.tableView addSubview:self.vedioBgView];


                  self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
                  self.vedioBgView.clipsToBounds = YES;

                   //GCD延迟
                  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                             self.vedioBgView.hidden = NO;
                      
                  });
                
                  break;
              }
                
          }

    }
    
}



-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //强制竖屏
    [self setViewOrientation:UIInterfaceOrientationPortrait];
    
//    [self.vedioView pausePlay];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
//    [self.vedioView continuePlay];
}


//全屏返回手势方法（写了下面的触摸点在子VC也能全屏手势返回）
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //因为方法里面它有if(self.vedioView.isPlaying_containPause == NO)这个判断、所以可以大胆使用、、、然后不需要之前播放哪个才播放哪个、因为它有headerView左VC右VC、所以按范围播放就行了、（这个VC我这里用了isPlaying没有用isPlaying_containPause、所以假如上一个VC是暂停不是停止的话、我这里可能也不会播放？估计不会的、因为对方VC在界面消失的时候停止了播放）
    [self scrollToStartPlay:[UIScrollView new]];
    
     self.isGoToHengVideoDetailVCToDisAppearView = NO;
    
    //把这个搬去了视频开始播放代理那里才可以旋转
    //让整个程序都可以旋转
//    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    appDelegate.allowRotate = 1;

}


- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    //这个无论是不是去横视频界面都去隐藏vedioBgView
    self.vedioBgView.hidden = YES;
    
    //假如是因为去横视频详情而离开本界面的不要去停止vedioView、、、去横视频VC可以旋转
    if (self.isGoToHengVideoDetailVCToDisAppearView) {
        return;
    }
    
    [self.vedioView stopPlay];
    
    //让整个程序不能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 0;
    
}



#pragma mark - 横屏模式


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    //我这里就不用了、除非你做个判断tableView有数据才去移动row、否则会崩
//    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.vedioView.index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
}
/**
 *  在此方法中修改布局
 */
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    
    // 布局
    if(isLanscape)
    {
        
        self.navBar.hidden = YES;
           
        self.view.backgroundColor = [UIColor blackColor];

        //它应该tabbar什么挡住了点击所以用[UIApplication sharedApplication].keyWindow不用self.view
        [[UIApplication sharedApplication].keyWindow addSubview:self.vedioBgView];
        
        self.vedioBgView.frame = CGRectMake(0, 0, Wi, He);
        
        self.vedioView.frame = self.vedioBgView.bounds;
        
        self.vedioBgView.layer.cornerRadius = 0;
        
        //因为这里有tabBar、所以要隐藏
        self.tabBarController.tabBar.hidden = YES;
        
        self.vedioView.bigScaleBtn.selected = YES;
        
        
    }else
    {
        
        self.navBar.hidden = NO;
        
        self.view.backgroundColor = [UIColor whiteColor];

        //加了这句就可以了、因为你把tableView的frame转换的时候tableView还是以横盘的参考对象、假如你写了layoutIfNeeded它就等你变成了竖屏再以竖屏的tableView为参考对象
        [self.view layoutIfNeeded];
        
        
        //把tabbar显示回出来
        self.tabBarController.tabBar.hidden = NO;
        
        self.vedioView.bigScaleBtn.selected = NO;
        
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.vedioView.index inSection:0];
        
        YWHomeRecommendVedioCell *vedioCell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        //转换父控件所在位置
        CGRect rects = [vedioCell.contentView convertRect:vedioCell.videoBgView.frame toView:self.tableView];

        self.vedioBgView.frame = rects;

        self.vedioView.frame = self.vedioBgView.bounds;
        
        //添加位置
        [self.tableView addSubview:self.vedioBgView];
        
        self.vedioBgView.layer.cornerRadius = vedioCell.videoBgView.layer.cornerRadius;
        self.vedioBgView.clipsToBounds = YES;
        
        
     
        
    }


}

//放大/缩小
-(void)videoView:(YWVideoView2 *)videoView didClickBigScaleBtn:(UIButton *)btn{
    
    
//    btn.selected = !btn.selected;
    if (self.vedioView.bigScaleBtn.selected) {
           [self setViewOrientation:UIInterfaceOrientationPortrait];
    }
    else{
        
           [self setViewOrientation:UIInterfaceOrientationLandscapeRight];
    }
}




//强制横屏或竖屏
-(void)setViewOrientation:(UIInterfaceOrientation)orientation{

    if (@available(iOS 16.0, *)) {
        [UIApplication.sharedApplication.keyWindow.rootViewController setNeedsUpdateOfSupportedInterfaceOrientations];
              
              NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
              UIWindowScene *ws = (UIWindowScene *)array[0];
              UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [UIWindowSceneGeometryPreferencesIOS.alloc initWithInterfaceOrientations:1 << orientation];
              [ws requestGeometryUpdateWithPreferences:geometryPreferences
                                          errorHandler:^(NSError * _Nonnull error) {
              }];
//            @try {
//                NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
//                UIWindowScene *ws = (UIWindowScene *)array[0];
//                Class GeometryPreferences = NSClassFromString(@"UIWindowSceneGeometryPreferencesIOS");
//                id geometryPreferences = [[GeometryPreferences alloc]init];
//
//                if(orientation == UIInterfaceOrientationPortrait) {
//                    [geometryPreferences setValue:@(UIInterfaceOrientationMaskPortrait) forKey:@"interfaceOrientations"];
//                }
//                else {
//                    [geometryPreferences setValue:@(UIInterfaceOrientationMaskLandscapeRight) forKey:@"interfaceOrientations"];
//                }
//
//                SEL sel_method = NSSelectorFromString(@"requestGeometryUpdateWithPreferences:errorHandler:");
//                void (^ErrorBlock)(NSError *err) = ^(NSError *err){
//                      NSLog(@"调用了Block%@",err);
//                };
//                if ([ws respondsToSelector:sel_method]) {
//                    (((void (*)(id, SEL,id,id))[ws methodForSelector:sel_method])(ws, sel_method,geometryPreferences,ErrorBlock));
//                }
//            } @catch (NSException *exception) {
//                NSLog(@"*****************************华丽分割线**************************");
//                NSLog(@"%@",exception);
//            } @finally {
//
//            }
        } else {
            
            if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
                SEL selector = NSSelectorFromString(@"setOrientation:");
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
                [invocation setSelector:selector];
                [invocation setTarget:[UIDevice currentDevice]];
                int val = (int)orientation;
                [invocation setArgument:&val atIndex:2];
                [invocation invoke];

            }

        }
    
    

}

//////

// 本VC可以支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

// 本VC是否支持设备自动旋转
- (BOOL)shouldAutorotate
{
    return YES;
}

/**
 *  当屏幕即将旋转的时候调用
 *  @param toInterfaceOrientation 旋转完毕后的最终方向
 *  @param duration  旋转动画所花费的时间
 */
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    
    //切换屏幕方向时候把videoFunctionView设为透明效果会好点
//    self.videoFunctionView.alpha = 0;

    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {// 横屏

    } else {//竖屏

    }

}

//开始成功代理
-(void)videoViewDidStartPlay:(YWVideoView2 *)videoView{
    
    //让整个程序能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 1;
    
    
}

//停止成功代理
-(void)videoViewDidSotpPlay:(YWVideoView2 *)videoView{
    
    //让整个程序不能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 0;
    
    
}





@end
